package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.WebsiteAddr;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_CORRELATIONARTICLE;

/**
 * 相关文章推荐,同一个分类下的文章
 *
 * @author chenfangzhou 2018/09/14
 */
@Component
@Slf4j
public class CorrelationArticleDirective extends AbstractDirective {
    @Autowired
    private ArticleServiceClient articleServiceClient;

    //站点id
    private static final String SITE_ID = "siteId";
    //文章id
    private static final String ARTICLE_ID = "articleId";
    //分类id
    private static final String COLUMN_ID = "columnId";
    //排序字段
    private static final String SORT = "sort";
    //获取文章的条数
    private static final String COUNT = "count";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            Long siteId = getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : getLong(SITE_ID, params);
            Long articleId = getLong(ARTICLE_ID, params) == null ? getArticleId(env) : getLong(ARTICLE_ID, params);
            Long columnId = getLong(COLUMN_ID, params) == null ? getColumnId(env) : getLong(COLUMN_ID, params);
            String sort = StringUtils.isBlank(getString(SORT, params)) ? "update_time" : getString(SORT, params);
            Integer count = getInt(COUNT, params) == null ? 7 : getInt(COUNT, params);
            String note = super.getNote(env);
            if (columnId == null) {
                log.debug("文章分类id为空!");
            }

            Article article_ = new Article();
            article_.setArticleId(articleId);
            article_.setSiteId(siteId);
            article_.setColumnId(columnId);
            article_.setSort(sort);
            article_.setCount(count);
            List<Article> correlationArticle = articleServiceClient.getCorrelationArticle(article_);
            WebsiteAddr webSiteAddr = getWebSiteAddr(siteId);
            if (StringUtils.isNotBlank(note)) {
                for (Article arc : correlationArticle) {
                    arc.setManuscriptPath(webSiteAddr.getIpAdd() + arc.getManuscriptPath());
                }
            }else {
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                String urlContext = siteCtxMap.get(siteId);
                // 静态文件文章链接加前缀
                if(StringUtils.isNotBlank(urlContext)) {
                    for (Article item : correlationArticle) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }
            env.setVariable("correlationArticle", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(correlationArticle));

            String userToken = super.getUserToken(env);
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_CORRELATIONARTICLE, "");
                    maps.put(SITE_ID, String.valueOf(getLong(SITE_ID, params)));
                    maps.put(ARTICLE_ID, String.valueOf(getLong(ARTICLE_ID, params)));
                    maps.put(SORT, String.valueOf(getLong(SORT, params)));
                    maps.put(COUNT, String.valueOf(getInt(COUNT, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                log.debug("文章详情所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
